/*-------------------   外部导入   -------------------------------------------------------------------*/
import type { ColumnsType } from 'antd/es/table';
import {
  useSearchParams,
  NavLink,
  useNavigate,
  useLocation
} from "react-router-dom";
import React from "react";
import { Card, Button, Row, Col, Input, Select, Table, message, Pagination, Modal } from "antd";
import { useState, useEffect } from "react";
// 导入接口
import {
  getCarList,  // 获取业主车辆信息
  getRelease, // 释放
  getDelete, // 删除
  getUpdate,  // 确定修改  
} from "../../../api/admin";
// 字体图标
import { PlusOutlined, SearchOutlined, RedoOutlined } from "@ant-design/icons";

/*-------------------   外部导入   -------------------------------------------------------------------*/

function listOwnerCar() {

  /*-------------------   定义数据   -------------------------------------------------------------------*/
  // 删除对话框
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 修改对话框
  const [isModify, setIsModify] = useState(false);

  // 修改对话框数据
  var arr = {
    "flowComponent": "addCar",
    "carNum": "车牌",
    "carBrand": "品牌",
    "carType": "9903",
    "carColor": "颜色",
    "remark": "备注",
    "startTime": "2023-05-01 21:31:48",
    "endTime": "2037-01-01",
    "leaseType": "NM",
    "carAttrs": "",
    "attrs": [
      {
        "domain": "COMMON",
        "listShow": "Y",
        "page": -1,
        "records": 0,
        "required": "N",
        "row": 0,
        "specCd": "6443000036",
        "specHoldplace": "业主车辆",
        "specId": "6443000036",
        "specName": "业主车辆",
        "specShow": "Y",
        "specType": "3344",
        "specValueType": "1001",
        "statusCd": "0",
        "tableName": "owner_car_attr",
        "total": 0,
        "value": "true",
        "values": [
          {
            "page": -1,
            "records": 0,
            "row": 0,
            "specId": "6443000036",
            "statusCd": "0",
            "total": 0,
            "value": "false",
            "valueId": "112022031522890163",
            "valueName": "否",
            "valueShow": "Y"
          },
          {
            "page": -1,
            "records": 0,
            "row": 0,
            "specId": "6443000036",
            "statusCd": "0",
            "total": 0,
            "value": "true",
            "valueId": "112022031502670160",
            "valueName": "是",
            "valueShow": "Y"
          }
        ]
      }
    ],
    "value": "",
    "index": 2,
    "communityId": "2023032658120002",
    "ownerId": localStorage.getItem("ownerId"),
    "psId": "792023042712642177"
  };
  const [modifyData, setModifyData] = useState(arr);

  const [messageApi, contextHolder] = message.useMessage(); 
  // 表格类型
    interface DataType {
      key: React.Key;
      name: string;
      age: number;
      address: string;
    }
  const navigate = useNavigate();
  // 表格标题--10个
  const columns: ColumnsType<DataType> = [
    {
      title: '车牌号',
      dataIndex: 'carNum',
      key:"carNum"
    },
    {
      title: '房间号',
      dataIndex: 'roomName',
      key:"roomName"
    },
    {
      title: '车牌类型',
      dataIndex: 'leaseTypeName',
      key:"leaseTypeName"
    },
    {
      title: '车辆类型',
      dataIndex: 'carTypeName',
      key:"carTypeName"
    },
    {
      title: '颜色',
      dataIndex: "carColor",
      key:"carColor"
    },
    {
      title: '业主',
      dataIndex: 'ownerName',
      key:"ownerName"
    },
    {
      title: '车位',
      dataIndex: 'areaNum',
      key:"areaNum"
    },
    {
      title: '有效期',
      dataIndex: 'startTime',
      key:"startTime"
    },
    {
      title: '状态',
      dataIndex: 'stateName',
      key:"stateName"
    },
    {
      title: '操作',
      dataIndex: 'carId',
      key:"carId",
      render:(carId,carNum)=><div>
          {carNum.stateName == "正常" ?
          <Button size="small" onClick={() => { release(carNum) }}>释放</Button>
          :
            <Button size="small" onClick={()=>{goListOwnerCar(carId,carNum)}}>续租</Button>
          }&ensp;
          <Button size="small" onClick={()=>{cost(carId,carNum)}}>费用</Button>&ensp;
        <Button size='small' onClick={() => { modify(carNum) }}>修改</Button>&ensp;
        <Button size='small' onClick={() => { del(carNum) }}>删除</Button>&ensp;
      </div>
    },
  ];
  const [button,setButton] = useState(1)
  const [userlist,setUserlist] = useState()
  var obj = [
    {name:"全部车辆",type:""},
    {name:"月租车",type:"H"},
    {name:"出租车",type:"S"},
    {name:"内部车",type:"I"},
    {name:"免费车",type:"NM"},
    {name:"预约车",type:"R"},
  ];
  // 定义查询参数
  var defaultParams:any = {
      carNum: "",
      carNumLike: "",
      num: "",
      valid: "",
      carTypeCd: "",
      leaseType: "H",
      ownerName: "",
      link: "",
      page: 1,
      row: 10,
      communityId: 2023032658120002
  }
  const [params,setParams] = useState(defaultParams)
  /*-------------------   定义数据   -------------------------------------------------------------------*/
  //  获取数据
  useEffect(() => {
    getCar()
  },[]);
  const getCar = (Type="H",index:any)=>{
    setParams({...params,leaseType:Type})
    setButton(index)
    getCarList(params)
      .then(res => {
      setUserlist(res.data.data)
    })
    console.log(button)
    console.log("obj",obj)
  }
  // 费用
  const cost = (e:any,z:any)=>{
    console.log(e,z)
    navigate(`/pages/property/listCarFee?carId=${z.carId}&carNum=${z.carNum}&areaNum=${z.areaNum}&num=${z.num}`);
  }
  // 续租
  const goListOwnerCar = (e:any,z:any)=>{
    console.log(e,z)
    navigate(`/pages/property/carAddParkingSpace?carId=${z.carId}`);
  }
  // 添加 
  const goHireParkingSpace = ()=>{
    navigate(`/pages/property/hireParkingSpace`);
  }
  // 释放
  const release = (e: any) => {
    getRelease(e).then(res => {
      message.success("释放成功！")
      console.log(res)
      getCar()
    })
  }

  // 删除
  const del = (e: any) => {
    console.log(e)
    // 会话存储
    localStorage.setItem("obj", JSON.stringify(e));
    setIsModalOpen(true);
  }
  // 确定删除
  const handleOk = () => {
    setIsModalOpen(false);
    // 获取本地存储
    var arr = JSON.parse(localStorage.getItem("obj") || '{}');
    getDelete(arr).then(res => {
      if (res.data.code != 200) {
        message.error(res.data.msg)
        return
      }
      message.success("删除成功！")
      getCar()
    })
  };
  // 点错了
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 修改
  const modify = (e: any) => {
    console.log(e)
    setModifyData(e);
    setIsModify(true);
  };
  // 确定修改
  const ModifyOk = () => {
    setIsModify(false);
    getUpdate(modifyData).then(res => {
      if (res.data.code != 0) {
        message.error(res.data.msg)
        return
      }
      message.success("修改成功！")
      getCar()
    })
  };
  // 取消修改
  const ModifyCancel = () => {
    setIsModify(false);
  };
  /*vvvvvvvvvvvvvvvvvvv   以下是DOM渲染内容  vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv*/
  return (
    <div className="listOwnerCar">
      <Modal title="修改" cancelText="取消" okText="确定" open={isModify} onOk={ModifyOk} onCancel={ModifyCancel}>
        <Card title="车辆信息">
          <Row gutter={24}>
            <Col span={4}>车牌号</Col>
            <Col span={20}>
              <Input placeholder="必填，请填写车牌号" allowClear
                value={modifyData.carNum} onChange={(e) => {
                  setModifyData({ ...modifyData, carNum: e.target.value })
                }}
              />
            </Col>
          </Row>
          <br />
          <Row gutter={24}>
            <Col span={4}>车品牌</Col>
            <Col span={20}>
              <Input placeholder="可选，请填写车品牌，如 宝马X6" allowClear
                value={modifyData.carBrand} onChange={(e) => {
                  setModifyData({ ...modifyData, carBrand: e.target.value })
                }}
              />
            </Col>
          </Row>
          <br />
          <Row gutter={24}>
            <Col span={4}>车类型</Col>
            <Col span={20}>
              <Select
                style={{ width: "100%" }}
                showSearch
                size="large"
                onChange={(e) => {
                  setModifyData({ ...modifyData, carType: e })
                }}
                placeholder="必填，请选择类型"
                optionFilterProp="children"
                filterOption={(input, option) =>
                  (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                }
                options={[
                  {
                    value: '9901',
                    label: '家用小汽车',
                  },
                  {
                    value: '9902',
                    label: '客车',
                  },
                  {
                    value: '9903',
                    label: '货车',
                  },
                  {
                    value: '9904',
                    label: '电动车',
                  },
                  {
                    value: '9905',
                    label: '三轮车',
                  },
                ]}
              />
            </Col>
          </Row>
          <br />
          <Row gutter={24}>
            <Col span={4}>颜色</Col>
            <Col span={20}>
              <Input placeholder="可选，请填写车颜色，如白色" allowClear
                value={modifyData.carColor} onChange={(e) => {
                  setModifyData({ ...obj, carColor: e.target.value })
                }} />
            </Col>
          </Row>
          <br />
          <Row gutter={24}>
            <Col span={4}>车牌类型</Col>
            <Col span={20}>
              <Select
                style={{ width: "100%" }}
                showSearch
                size="large"
                onChange={(e) => {
                  setModifyData({ ...obj, leaseType: e })
                }}
                placeholder="必填，请选择车牌类型"
                optionFilterProp="children"
                filterOption={(input, option) =>
                  (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                }
                options={[
                  {
                    value: 'H',
                    label: '月租车',
                  },
                  {
                    value: 'S',
                    label: '出售车辆',
                  },
                  {
                    value: 'I',
                    label: '内部车',
                  },
                  {
                    value: 'NM',
                    label: '免费车',
                  },
                ]}
              />
            </Col>
          </Row>
          <br />
          <Row gutter={24}>
            <Col span={4}>备注</Col>
            <Col span={20}>
              <Input placeholder="请填写备注信息" allowClear
                value={modifyData.remark} onChange={(e) => {
                  setModifyData({ ...modifyData, remark: e.target.value })
                }} />
            </Col>
          </Row>
        </Card>
      </Modal>

      <Modal title="请确认您的操作!" cancelText="点错了" okText="确定删除" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <p>确认是否删除!</p>
      </Modal>
      <Row gutter={24}>
        {/* 左侧按钮选项 */}
        <Col span={4}>
          <div className="but">
              {
                obj.map((item,index)=>
                  <button key={index} className='butn' size="large" id={button==index ? "but_on":"but_in"} onClick={()=>{getCar(item.type,index)}}>{item.name}</button>
                )
              }
          </div>
        </Col>

        {/* 右侧表格信息 */}
        <Col span={20}>
          <Card title="查询条件">
            <Row gutter={24}>
              <Col span={6}>
                <Input placeholder="请输入车牌号" style={{ height: "40px" }}  
                  value={params.carNumLike} onChange={(e) => {
                    setParams({...params,carNumLike:e.target.value})
                  }}
                />
              </Col>
              <Col span={8}>
                <Input placeholder="请填写车位编号" style={{ height: "40px" }} 
                  value={params.num} onChange={(e) => {
                  setParams({...params,num:e.target.value})
                }}/>
              </Col>
              <Col span={5}>
                <Select
                 style={{width:"100%" }}
                  showSearch
                  size="large"
                  placeholder="必填，请选择车位状态"
                  optionFilterProp="children"
                  // onChange={onChange}
                  // onSearch={onSearch}
                  filterOption={(input, option) =>
                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                  }
                  options={[
                    {
                      value: 'jack',
                      label: 'Jack',
                    },
                    {
                      value: 'lucy',
                      label: 'Lucy',
                    },
                    {
                      value: 'tom',
                      label: 'Tom',
                    },
                  ]}
                />
              </Col>
              <Col span={5}>
                <Button
                  type="primary"
                  icon={<SearchOutlined />}
                  style={{ height: "40px" }}
                  onClick={getCar}
                >
                  搜索
                </Button>
                &ensp;<Button
                  type="primary"
                  icon={<RedoOutlined />}
                  style={{ height: "40px" }}
                >
                  重置
                </Button>
              </Col>
            </Row>
            <Row gutter={24} style={{ marginTop: 16 }}>
              <Col span={6}>
                <Input placeholder="请填写业主名称" style={{ height: "40px" }} 
                  value={params.ownerName} onChange={(e) => {
                  setParams({...params,ownerName:e.target.value})
                }}/>
              </Col>
              <Col span={8}>
                <Input placeholder="请输入联系方式" style={{ height: "40px" }} 
                  value={params.link} onChange={(e) => {
                  setParams({...params,link:e.target.value})
                }}/>  
              </Col>
            </Row>
          </Card>

          <Card
            style={{ marginTop: 16 }}
            title="车辆信息"
            extra={
              <div>
                <Button type="primary" icon={<PlusOutlined />} onClick={()=>{goHireParkingSpace()}}>
                  物业费
                </Button>&emsp;
                <Button>物业费</Button>
              </div>
            }
          >
            <Table columns={columns} dataSource={userlist} size="middle" />
          </Card>
        </Col>
      </Row>
    </div>
  );
}

export default listOwnerCar;
